package com.iceframework.core.entity;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

/**
 * 分页存储
 * 
 * @author Palo
 *
 */
public class Page<E> extends com.github.pagehelper.Page<E> {

	private static final long serialVersionUID = 1545854596614149376L;

	private String orderByColumn;
	private String isAsc = "asc";

	public String getOrderByColumn() {
		return orderByColumn;
	}

	public void setOrderByColumn(String orderByColumn) {
		this.orderByColumn = orderByColumn;
	}

	public String getIsAsc() {
		return isAsc;
	}

	public void setIsAsc(String isAsc) {
		this.isAsc = isAsc;
	}
	
	/**
	 * key 实体栏位 value 数据库栏位
	 * @param orderByStr key1=value1,key2=value2
	 * @return
	 */
	public String getOrderByScript(String orderByStr) {
		Map<String, String> orderByMap = convertOrderByMap(orderByStr);
		String orderBy = super.getOrderBy();
		if(StringUtils.isNotEmpty(orderBy)) {
			return orderBy;
		} else if(StringUtils.isNotEmpty(getOrderByColumn())) {
			String column = getOrderByColumn().trim();
			if(StringUtils.isEmpty(column)) {
				return null;
			}
			String dbColumn = orderByMap.get(column);
			if(StringUtils.isNotEmpty(getIsAsc()) && "desc".equals(getIsAsc().trim().toLowerCase())) {
				return dbColumn + " desc";
			}
			return dbColumn + " asc";
		}
		return null;
	}
	
	private Map<String,String> convertOrderByMap(String orderByStr) {
		String[] split = orderByStr.split(",");
		Map<String, String> orderByMap = new HashMap<String, String>();
		for (String string : split) {
			String[] split2 = string.split("=");
			if(split2.length==2 && StringUtils.isNotEmpty(split2[0]) && StringUtils.isNotEmpty(split2[1])) {
				orderByMap.put(split2[0].trim(), split2[1].trim());
			}
		}
		return orderByMap;
	}

}